<template>
  <div class="flex flex-col gap-4">
    <div class="flex items-center justify-between">
      <h1 class="text-3xl font-bold tracking-tight">媒体管理</h1>
      <router-link to="/media/new">
        <Button>
          <PlusCircle class="mr-2 h-4 w-4" />
          添加媒体
        </Button>
      </router-link>
    </div>

    <Card>
      <CardHeader>
        <CardTitle>媒体管理</CardTitle>
        <CardDescription>管理单词的图片、音频和其他媒体。</CardDescription>
      </CardHeader>
      <CardContent>
        <div class="flex flex-col md:flex-row gap-4 justify-between items-center pb-4">
          <Input
              placeholder="搜索媒体..."
              class="md:max-w-sm w-full"
              v-model="searchQuery"
              @input="handleSearchInput"
          />
          <Select v-model="selectedType" @update:modelValue="handleTypeChange">
            <SelectTrigger class="w-[180px]">
              <SelectValue placeholder="媒体类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">所有类型</SelectItem>
              <SelectItem value="image">图片</SelectItem>
              <SelectItem value="audio">音频</SelectItem>
              <SelectItem value="video">视频</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>ID</TableHead>
              <TableHead>单词</TableHead>
              <TableHead>媒体类型</TableHead>
              <TableHead>预览</TableHead>
              <TableHead>URL</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow v-for="media in mediaItems" :key="media.id">
              <TableCell>{{ media.id }}</TableCell>
              <TableCell>{{ media.word }}</TableCell>
              <TableCell>
                <span
                    class="px-2 py-1 text-xs rounded-full"
                    :class="{
                    'bg-blue-100 text-blue-800': media.mediaType === 'image',
                    'bg-green-100 text-green-800': media.mediaType === 'audio',
                    'bg-purple-100 text-purple-800': media.mediaType === 'video'
                  }"
                >
                  {{
                    media.mediaType === 'image' ? '图片' :
                        media.mediaType === 'audio' ? '音频' : '视频'
                  }}
                </span>
              </TableCell>
              <TableCell>
                <img
                    v-if="media.mediaType === 'image'"
                    :src="media.url || '/placeholder.svg'"
                    :alt="`${media.word} 的预览`"
                    class="h-10 w-16 object-cover rounded"
                />
                <div
                    v-else-if="media.mediaType === 'audio'"
                    class="h-10 w-16 flex items-center justify-center bg-secondary rounded"
                >
                  <span class="text-xs">音频</span>
                </div>
                <div
                    v-else
                    class="h-10 w-16 flex items-center justify-center bg-secondary rounded"
                >
                  <span class="text-xs">视频</span>
                </div>
              </TableCell>
              <TableCell class="max-w-[200px] truncate">{{ media.url }}</TableCell>
              <TableCell>
                <DropdownMenu>
                  <DropdownMenuTrigger as-child>
                    <Button variant="ghost" class="h-8 w-8 p-0">
                      <span class="sr-only">打开菜单</span>
                      <MoreHorizontal class="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem @click="openPreviewDialog(media)">
                      <Eye class="mr-2 h-4 w-4" />
                      预览
                    </DropdownMenuItem>
                    <DropdownMenuItem @click="router.push(`/media/${media.id}/edit`)">
                      <Pencil class="mr-2 h-4 w-4" />
                      编辑
                    </DropdownMenuItem>
                    <DropdownMenuItem @click="handleDownload(media)">
                      <Download class="mr-2 h-4 w-4" />
                      下载
                    </DropdownMenuItem>
                    <DropdownMenuItem
                        class="text-destructive focus:text-destructive"
                        @click="openDeleteDialog(media)"
                    >
                      <Trash class="mr-2 h-4 w-4" />
                      删除
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>

        <!-- 分页控件 -->
        <div class="flex items-center justify-between px-2 py-4">
          <div class="flex-1 text-sm text-muted-foreground">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页，显示 {{ (currentPage - 1) * pageSize + 1 }}-{{ Math.min(currentPage * pageSize, totalItems) }} 条，共 {{ totalItems }} 条
          </div>
          <div class="flex items-center space-x-2">
            <Button
                variant="outline"
                size="sm"
                :disabled="currentPage === 1"
                @click="goToPage(currentPage - 1)"
            >
              上一页
            </Button>

            <!-- 页码输入框 -->
            <div class="flex items-center space-x-1">
              <span class="text-sm text-muted-foreground">前往</span>
              <Input
                  type="number"
                  :min="1"
                  :max="totalPages"
                  class="w-16 h-8 text-center"
                  v-model="pageInput"
                  @keyup.enter="goToInputPage"
              />
              <span class="text-sm text-muted-foreground">页</span>
            </div>

            <div class="flex items-center space-x-1">
              <Button
                  v-for="page in visiblePages"
                  :key="page"
                  variant="outline"
                  size="sm"
                  :class="currentPage === page ? 'bg-primary text-primary-foreground' : ''"
                  @click="goToPage(page)"
              >
                {{ page }}
              </Button>
              <span v-if="showEllipsis" class="px-2">...</span>
            </div>
            <Button
                variant="outline"
                size="sm"
                :disabled="currentPage === totalPages || totalPages === 0"
                @click="goToPage(currentPage + 1)"
            >
              下一页
            </Button>
            <Select v-model="pageSize" @update:modelValue="handlePageSizeChange">
              <SelectTrigger class="w-24">
                <SelectValue placeholder="选择数量" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem :value="10">10 条/页</SelectItem>
                <SelectItem :value="20">20 条/页</SelectItem>
                <SelectItem :value="50">50 条/页</SelectItem>
                <SelectItem :value="100">100 条/页</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
      </CardContent>
    </Card>

    <!-- 删除确认对话框 -->
    <AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>确定要删除吗？</AlertDialogTitle>
          <AlertDialogDescription>
            此操作无法撤消。这将永久从服务器和数据库中删除此媒体文件。
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>取消</AlertDialogCancel>
          <AlertDialogAction
              @click="confirmDelete"
              class="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            删除
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>

    <!-- 预览对话框 -->
    <Dialog :open="showPreviewDialog" @update:open="showPreviewDialog = $event">
      <DialogContent class="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>媒体预览</DialogTitle>
          <DialogDescription v-if="selectedMedia">
            {{ selectedMedia.word }} 的{{
              selectedMedia.mediaType === 'image' ? '图片' :
                  selectedMedia.mediaType === 'audio' ? '音频' : '视频'
            }}
          </DialogDescription>
        </DialogHeader>
        <div class="flex items-center justify-center p-4" v-if="selectedMedia">
          <img
              v-if="selectedMedia.mediaType === 'image'"
              :src="selectedMedia.url || '/placeholder.svg'"
              :alt="`${selectedMedia.word} 的预览`"
              class="max-h-[300px] object-contain"
          />
          <audio
              v-else-if="selectedMedia.mediaType === 'audio'"
              controls
              class="w-full"
          >
            <source :src="selectedMedia.url" type="audio/mpeg" />
            您的浏览器不支持音频元素。
          </audio>
          <video
              v-else
              controls
              class="max-h-[300px]"
          >
            <source :src="selectedMedia.url" type="video/mp4" />
            您的浏览器不支持视频元素。
          </video>
        </div>
      </DialogContent>
    </Dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '@/components/ui/toast'
import {
  PlusCircle,
  MoreHorizontal,
  Eye,
  Pencil,
  Trash,
  Download
} from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle
} from '@/components/ui/dialog'
import mediaAPI from '@/api/media.js'

const router = useRouter()
const { toast } = useToast()
const searchQuery = ref('')
const selectedType = ref('all')
const showDeleteDialog = ref(false)
const showPreviewDialog = ref(false)
const selectedMedia = ref(null)
const pageInput = ref('')

const mediaItems = ref([])

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = ref(0)
const allMediaItems = ref([]) // 存储所有媒体数据
const loading = ref(false)

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalItems.value / pageSize.value) || 1
})

// 计算可见的页码按钮
const visiblePages = computed(() => {
  const pages = []
  const maxVisiblePages = 5

  if (totalPages.value <= 1) return []

  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2))
  let endPage = Math.min(totalPages.value, startPage + maxVisiblePages - 1)

  if (endPage - startPage + 1 < maxVisiblePages) {
    startPage = Math.max(1, endPage - maxVisiblePages + 1)
  }

  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }

  return pages
})

// 是否显示省略号
const showEllipsis = computed(() => {
  return totalPages.value > visiblePages.value.length &&
      visiblePages.value[visiblePages.value.length - 1] < totalPages.value
})

const fetchMediaItems = async () => {
  try {
    loading.value = true
    const response = await mediaAPI.getMedias({
      search: searchQuery.value,
      type: selectedType.value !== 'all' ? selectedType.value : undefined
    })

    if (response.code === 200) {
      allMediaItems.value = response.data
      totalItems.value = response.data.length
      updateDisplayedMediaItems()
    }
  } catch (error) {
    console.error(error)
    toast({
      title: "获取失败",
      description: "获取媒体列表时发生错误。",
      variant: "destructive",
    })
  } finally {
    loading.value = false
  }
}

// 更新显示的媒体列表
const updateDisplayedMediaItems = () => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  // 如果有搜索查询或类型筛选，先过滤数据
  let filteredMedia = allMediaItems.value
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filteredMedia = allMediaItems.value.filter(m =>
        m.word.toLowerCase().includes(query)
    )
  }

  if (selectedType.value !== 'all') {
    filteredMedia = filteredMedia.filter(m => m.mediaType === selectedType.value)
  }

  totalItems.value = filteredMedia.length
  mediaItems.value = filteredMedia.slice(startIndex, startIndex + pageSize.value)

  // 如果当前页没有数据且不是第一页，回到上一页
  if (mediaItems.value.length === 0 && currentPage.value > 1) {
    currentPage.value = Math.max(1, Math.ceil(totalItems.value / pageSize.value))
    updateDisplayedMediaItems()
  }

  pageInput.value = ''
}

// 跳转到指定页
const goToPage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  updateDisplayedMediaItems()
}

// 处理输入框跳转
const goToInputPage = () => {
  if (!pageInput.value) return

  const pageNum = parseInt(pageInput.value)
  if (isNaN(pageNum) || pageNum < 1 || pageNum > totalPages.value) {
    toast({
      title: "输入错误",
      description: `请输入有效的页码 (1-${totalPages.value})`,
      variant: "destructive"
    })
    pageInput.value = ''
    return
  }

  goToPage(pageNum)
}

// 处理每页显示数量变化
const handlePageSizeChange = (newSize) => {
  pageSize.value = parseInt(newSize)
  currentPage.value = 1 // 重置到第一页
  updateDisplayedMediaItems()
}

// 处理搜索输入（防抖）
const handleSearchInput = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    currentPage.value = 1 // 搜索时重置到第一页
    updateDisplayedMediaItems()
  }, 300)
}

let searchTimeout

// 处理类型筛选变化
const handleTypeChange = () => {
  currentPage.value = 1 // 类型筛选时重置到第一页
  updateDisplayedMediaItems()
}

const confirmDelete = async () => {
  if (!selectedMedia.value) return

  try {
    const response = await mediaAPI.deleteMedia(selectedMedia.value.id)

    if (response.code === 200) {
      // 从列表中移除
      const index = allMediaItems.value.findIndex(item => item.id === selectedMedia.value.id)
      if (index !== -1) {
        allMediaItems.value.splice(index, 1)
        totalItems.value = allMediaItems.value.length
        updateDisplayedMediaItems()
      }

      toast({
        title: "媒体已删除",
        description: "媒体文件已成功从服务器删除。",
      })
    }
  } catch (error) {
    console.error(error)
    toast({
      title: "删除失败",
      description: "删除媒体文件时发生错误。",
      variant: "destructive",
    })
  } finally {
    showDeleteDialog.value = false
    selectedMedia.value = null
  }
}

const openDeleteDialog = (media) => {
  selectedMedia.value = media
  showDeleteDialog.value = true
}

const openPreviewDialog = (media) => {
  selectedMedia.value = media
  showPreviewDialog.value = true
}

const handleDownload = (media) => {
  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = media.url
    link.download = media.word + '_' + media.id
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    toast({
      title: "开始下载",
      description: `正在下载 ${media.word} 的媒体文件。`,
    })
  } catch (error) {
    console.error('下载失败:', error)
    toast({
      title: "下载失败",
      description: "下载媒体文件时发生错误。",
      variant: "destructive",
    })
  }
}

// 监听搜索查询和类型变化
watch([searchQuery, selectedType], () => {
  currentPage.value = 1 // 重置到第一页
  updateDisplayedMediaItems()
})

onMounted(() => {
  fetchMediaItems()
})
</script>
